import React, {useEffect, useRef, useState} from 'react';
import {Breadcrumb, Button, Card, Form, Input, message, Radio, Select, Space, Upload} from "antd";
import {Link, useLocation, useNavigate, useSearchParams} from "react-router-dom";
import {Option} from "antd/es/mentions";
import {PlusOutlined} from "@ant-design/icons";
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import './index.scss'
import {useStore} from "@/store";
import {observer} from "mobx-react-lite";
import {http} from "@/utils";

const Publish = () => {

    //面包屑
    const items = [// 菜单项务必填写 key
        {label: <Link to="/publish">发布文章</Link>, key: '/publish'},
    ];
    const {channelStore} = useStore()

    //存放上传图片的列表
    const [fileList, setFileList] = useState([])

    //useRef声明一个暂存仓库
    const cacheImgList = useRef()
    //上传图片事件
    const onUploadChange = ({fileList}) => {
        // 采取受控的写法:在最后一次log里response
        // 最终react state fileList中存放的数据有response.data.url
        // console.log(fileList)
        //同时把图片列表存入仓库一份
        //这里关键位置:需要做数据格式化
        const formatList = fileList.map(file => {
            //上传完毕
            if (file.response) {
                return {
                    url: file.response.data.url
                }
            }
            //否则上传中时不做处理
            return file
        })
        setFileList(formatList)
        cacheImgList.current = fileList
    }

    //切换图片
    const [imgCount, setImgCount] = useState(1)
    const radioChange = (e) => {
        // 这里的判断依据我们采取原始值不采取经过useState方法修改之后的数据
        // useState修改之后的数据无法同步获取修改之后的新值
        let rawValue = e.target.value
        setImgCount(rawValue)
        // console.log(e.target.value)
        // console.log(imgCount)
        //从仓库里边取对应的 图片数量交给我们用来渲染图片列表的fileList
        // 交给我们用来渲染图片列表的fileList
        if (rawValue === 1) {
            let img = cacheImgList.current ? cacheImgList.current[0] : []
            setFileList([img])
        } else if (rawValue === 3) {
            setFileList(cacheImgList.current)
        }
    }

    //提交表单
    const navigate = useNavigate()
    const onFinish = async (values) => {
        console.log(values)
        //数据的二次处理,重点是处理cover字段
        const {channel_id, content, title, type} = values
        const params = {
            channel_id,
            content,
            title,
            type,
            cover: {
                type,
                images: fileList.map(item => item.url)
            }
        }
        if (id) {
            await http.put(`/mp/articles/${id}?draft=false`, params)
        } else {
            await http.post('/mp/articles?draft=false', params)
        }
        navigate('/article')
        message.success(`${id ? '更新文章成功!' : '发布文章成功!'}`)
    }

    //编辑功能拿到文章ID
    //文案适配路由参数id判断条件
    // const {search} = useLocation()
    // const id = search.slice(4)
    // console.log(id)
    const [params] = useSearchParams()
    const id = params.get('id')
    const formRef = useRef(null)
    //数据回填 id调用接口   1.表单回填 2.暂存列表 3.Upload组件 fileList
    useEffect(() => {
        const getDetail = async () => {
            const {data} = await http.get(`/mp/articles/${id}`)
            const formatImgList = data.cover.images.map(url => ({url}))
            // console.log(res)
            //表单数据回填setFieldsValue
            formRef.current.setFieldsValue({...data, type: data.cover.type})
            //调用setFileList()回填upload
            setFileList(formatImgList)
            //暂存列表里也存一份(暂存列表和fileList回显列表保持数据格式统一)
            cacheImgList.current = formatImgList
        }
        //必须是编辑状态才可以发送请求
        if (id) {
            getDetail()
        }
    }, [id])


    return (
        <Card
            className="publish"
            style={{marginBottom: 20}}
            title={
                <Breadcrumb separator='>'>
                    <Breadcrumb.Item>
                        <Link to={'/'}>首页</Link>
                    </Breadcrumb.Item>
                    {items.map(item =>
                        <Breadcrumb.Item key={item.key}>
                            {id ? '编辑文章' : item.label}
                        </Breadcrumb.Item>)}
                </Breadcrumb>}>

            <Form
                ref={formRef}
                onFinish={onFinish}
                labelCol={{span: 4}}
                wrapperCol={{span: 16}}
                // 注意：此处需要为富文本编辑表示的 content 文章内容设置默认值
                initialValues={{type: 1, content: ''}}>
                <Form.Item label="标题" name="title"
                           rules={[{required: true, message: '请输入文章标题'}]}>
                    <Input placeholder="请输入文章标题" style={{width: 400}}/>
                </Form.Item>
                <Form.Item label="频道" name="channel_id" rules={[{required: true, message: '请选择文章频道'}]}>
                    <Select
                        placeholder="请选择文章频道"
                        style={{width: 400}}
                        options={
                            channelStore.channelList.map(item => ({value: item.id, label: item.name}))
                        }
                    />
                </Form.Item>
                <Form.Item label="封面">
                    <Form.Item name="type">
                        <Radio.Group onChange={radioChange}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {imgCount > 0 && <Upload
                        name="image"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList
                        action="http://geek.itheima.net/v1_0/upload"
                        fileList={fileList}
                        onChange={onUploadChange}
                        multiple={imgCount > 1}
                        maxCount={imgCount}
                    >
                        <div style={{marginTop: 8}}>
                            <PlusOutlined/>
                        </div>
                    </Upload>}
                </Form.Item>
                <Form.Item
                    label="内容"
                    name="content"
                    rules={[{required: true, message: '请输入文章内容'}]}>
                    {/*这里的富文本组件已经被Form. Item控制*/}
                    {/*它的输入内容会在onFinished回调中收集起来*/}
                    <ReactQuill className="publish-quill"
                                theme="snow"
                                placeholder="请输入文章内容"/>
                </Form.Item>
                <Form.Item wrapperCol={{offset: 4}}>
                    <Space>
                        <Button size="large" type="primary" htmlType="submit">
                            {id ? '更新' : '发布'}文章
                        </Button>
                    </Space>
                </Form.Item>
            </Form>

        </Card>
    );
};

export default observer(Publish);